package com.juno.cafeNoa.admin;

import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.google.android.gcm.GCMRegistrar;
import com.juno.cafeNoa.admin.adapter.AverageADP;
import com.juno.cafeNoa.admin.adapter.EventADP;
import com.juno.cafeNoa.admin.adapter.MemberADP;
import com.juno.cafeNoa.admin.adapter.OrderADP;
import com.juno.cafeNoa.admin.data.Average;
import com.juno.cafeNoa.admin.data.Event;
import com.juno.cafeNoa.admin.data.Member;
import com.juno.cafeNoa.admin.data.Order;
import com.juno.cafeNoa.admin.dummy.DummyContent;
import com.juno.cafeNoa.admin.listener.EventListCompelete;
import com.juno.cafeNoa.admin.listener.OrderListCompelete;
import com.juno.cafeNoa.admin.net.AsyncTaskCompleteListener;
import com.juno.cafeNoa.admin.net.HttpPostTask;
import com.juno.cafeNoa.admin.net.NetConstant;
import com.juno.cafeNoa.admin.util.Util;

public class ItemDetailFragment extends Fragment implements OnClickListener{
	public static final String ARG_ITEM_ID = "item_id";
	private DummyContent.DummyItem mItem;
	private Button btn;
	private ListView list;
	private ArrayList<Member> memberList;
	private ArrayList<Order> orderList;
	private ArrayList<Average> averageList;
	private ArrayList<Event> eventList;
	private MemberADP memberAdapter;
	private OrderADP orderAdapter;
	private AverageADP averageAdapter;
	private EventADP eventAdapter;
	
	//event regedit 관련 변수
	private Button startTimeBtn, endTimeBtn;
	private Button completeBtn;
	
	private EditText etEventTitle;
	private EditText etEventContent;
	
	private CheckBox cbSurpriseEvent;
	////////////////////////////////
	//date picker에 이용할 변수
	int mYear;
	int mMonth;
	int mDate;
	int mTime;
	int mMinute;

		
	private Context mContext;
	
	private ProgressDialog progress;
	public ItemDetailFragment() {
	
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		if (getArguments().containsKey(ARG_ITEM_ID)) {
			mItem = DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
		}
		
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDate = c.get(Calendar.DAY_OF_MONTH);
        mTime = c.get(Calendar.HOUR);
        mMinute = c.get(Calendar.MINUTE);
	}
	
	

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.mContext = activity;
	}
	
	private final int MEMBER_LIST = 1001;
	private final int ORDER_LIST = 1002;
	private final int AVERAGE_LIST = 1003;
	private final int EVENT_LIST = 1004;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(mItem.layoutId, container, false);
		if(mItem!=null){
			
			memberAdapter = null;
			orderAdapter = null;
			averageAdapter = null;
			memberList = null;
			orderList = null;
			averageList = null;
			progress = new ProgressDialog(mContext);
			progress.setMessage("로딩중입니다..");
			progress.setTitle("CAFE NOA");
			progress.setIcon(R.drawable.ic_launcher);
			
			switch(mItem.layoutId){
				case R.layout.fragment_list_member:{
					progress.show();
					list = (ListView) rootView.findViewById(R.id.lv_member);
					btn = (Button) rootView.findViewById(R.id.refresh_member);
					btn.setId(MEMBER_LIST);
					memberList = new ArrayList<Member>();
					
					memberAdapter = new MemberADP(mContext, R.layout.row_member, memberList);
					list.setAdapter(memberAdapter);
										
					getMemberListener.excuteHttpTask();
					btn.setOnClickListener(this);

					break;
				}
				case R.layout.fragment_list_average:{
					progress.show();

					list = (ListView) rootView.findViewById(R.id.lv_average);
					btn = (Button) rootView.findViewById(R.id.refresh_average);
					btn.setId(AVERAGE_LIST);

					averageList = new ArrayList<Average>();
					
					averageAdapter = new AverageADP(mContext, R.layout.row_average, averageList);
					list.setAdapter(averageAdapter);
										
					getAverageListener.excuteHttpTask();
					btn.setOnClickListener(this);

					break;
				}
				case R.layout.fragment_list_event:{
					progress.show();

					list = (ListView) rootView.findViewById(R.id.lv_event);
					btn = (Button) rootView.findViewById(R.id.refresh_event);
					btn.setId(EVENT_LIST);

					eventList = new ArrayList<Event>();
					
					eventAdapter = new EventADP(mContext, R.layout.row_event, eventList);
					eventAdapter.setListener(new EventListCompelete(){

						@Override
						public void EventComplete(boolean flag, int position) {
							if(flag){
								eventList.remove(position);
								eventAdapter.notifyDataSetChanged();
							}							
						}
						
					});
					list.setAdapter(eventAdapter);
										
					getEventListener.excuteHttpTask();
					btn.setOnClickListener(this);

					break;
				}
				case R.layout.fragment_list_order:{
					progress.show();

					list = (ListView) rootView.findViewById(R.id.lv_order);
					btn = (Button) rootView.findViewById(R.id.refresh_order);
					btn.setId(ORDER_LIST);
					orderList = new ArrayList<Order>();
					
					orderAdapter = new OrderADP(mContext, R.layout.row_order, orderList);
					orderAdapter.setListener(new OrderListCompelete(){

						@Override
						public void OrderComplete(boolean flag, int position) {
							if(flag){
								orderList.remove(position);
								orderAdapter.notifyDataSetChanged();
							}
						}
						
					});
					
					list.setAdapter(orderAdapter);
										
					getOrderListener.excuteHttpTask();
					btn.setOnClickListener(this);

					break;
				}
				case R.layout.fragment_event_regidit:{
					startTimeBtn = (Button) rootView.findViewById(R.id.btnStartDate);
					endTimeBtn = (Button) rootView.findViewById(R.id.btnEndDate);
					completeBtn = (Button) rootView.findViewById(R.id.btnRegedit);
					
					etEventTitle = (EditText) rootView.findViewById(R.id.etEventTitle);
					etEventContent = (EditText) rootView.findViewById(R.id.etEventCommand);
					
					cbSurpriseEvent =(CheckBox) rootView.findViewById(R.id.cbSurpriceEvent);
					startTimeBtn.setOnClickListener(this);
					endTimeBtn.setOnClickListener(this);
					completeBtn.setOnClickListener(this);

					break;
				}
			}
			
		}
		return rootView;
	}
	
	AsyncTaskCompleteListener getMemberListener = new AsyncTaskCompleteListener(){

		@Override
		public void excuteHttpTask() {
			String url = Util.getUrl("GetMemberList");
			
			ArrayList<NameValuePair> value = new ArrayList<NameValuePair>();
			value.add(new BasicNameValuePair("REQUEST_ID", "100"));
			
			HttpPostTask http = new HttpPostTask(mContext, value, url, getMemberListener);
			http.execute();
		}

		@Override
		public void onTaskComplete(String result, boolean taskOk) {
			Log.v("result","reuslt :" + result);
			if(taskOk){
				int code = -1;
				
				try {
					JSONObject object = new JSONObject(result);
					code = object.getInt("RESULT");

					if(code==NetConstant.NETWORK_SUCCESS){
						JSONArray jArr = object.getJSONArray("ITEM");
						
						String id = null;
						String phone = null;
						int point = -1;
						boolean black = false;
						boolean grade = false;
						
						for(int i=0;i<jArr.length();i++){
							JSONObject obj = jArr.getJSONObject(i);
							id = obj.getString("USER_ID");
							phone = obj.getString("USER_PHONE");
							point = obj.getInt("USER_POINT");
							String bTemp = obj.getString("USER_BLACK");
							String gTemp =obj.getString("USER_GRADE"); 

							black = (bTemp.equalsIgnoreCase("1")) ? true : false;
	
							grade = (gTemp.equalsIgnoreCase("1")) ? true : false;
							
							memberList.add(new Member(id, phone, grade, point, black));
						}
						memberAdapter.notifyDataSetChanged();
						list.invalidate();
						progress.dismiss();

					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		
	};
	
	AsyncTaskCompleteListener getAverageListener = new AsyncTaskCompleteListener(){

		@Override
		public void excuteHttpTask() {
			String url = Util.getUrl("AverageList");
			
			ArrayList<NameValuePair> value = new ArrayList<NameValuePair>();
			value.add(new BasicNameValuePair("REQUEST_ID", "100"));
			
			HttpPostTask http = new HttpPostTask(mContext, value, url, getAverageListener);
			http.execute();
		}

		@Override
		public void onTaskComplete(String result, boolean taskOk) {
			Log.v("result","reuslt :" + result);
			if(taskOk){
				int code = -1;
				
				try {
					JSONObject object = new JSONObject(result);
					code = object.getInt("RESULT");

					if(code==NetConstant.NETWORK_SUCCESS){
						JSONArray jArr = object.getJSONArray("ITEM");
						String date = null;
						int amount = -1;
						int card = -1;
						int point = -1;
						int visit = -1;
												
						
						for(int i=0;i<jArr.length();i++){
							JSONObject obj = jArr.getJSONObject(i);
							date = obj.getString("SELL_DATE");
							amount = obj.getInt("SELL_AMOUNT");
							card = obj.getInt("SELL_CARD");
							point = obj.getInt("SELL_POINT");
							visit = obj.getInt("SELL_VISIT");
						
							averageList.add(new Average(date, amount, card, point, visit));
						}
						averageAdapter.notifyDataSetChanged();
						list.invalidate();
						progress.dismiss();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		
	};
	
	
	AsyncTaskCompleteListener getOrderListener = new AsyncTaskCompleteListener(){

		@Override
		public void excuteHttpTask() {
			String url = Util.getUrl("GetOrderList");
			
			ArrayList<NameValuePair> value = new ArrayList<NameValuePair>();
			value.add(new BasicNameValuePair("REQUEST_ID", "100"));
			
			HttpPostTask http = new HttpPostTask(mContext, value, url, getOrderListener);
			http.execute();
		}

		@Override
		public void onTaskComplete(String result, boolean taskOk) {
			Log.v("result","reuslt :" + result);
			if(taskOk){
				int code = -1;
				
				try {
					JSONObject object = new JSONObject(result);
					code = object.getInt("RESULT");

					if(code==NetConstant.NETWORK_SUCCESS){
						JSONArray jArr = object.getJSONArray("ITEM");
						int orderNumber = -1;
						String content = null;
						String comment = null;
						String pickup = null;
						String method = null;
						int price = -1;
						String userId = null;
												
						
						for(int i=0;i<jArr.length();i++){
							JSONObject obj = jArr.getJSONObject(i);
							orderNumber= obj.getInt("ORDER_NUMBER");
							content = obj.getString("ORDER_CONTENT");
							comment = obj.getString("ORDER_COMMENT");
							pickup = obj.getString("ORDER_PICKUP_TIME");
							method = obj.getString("ORDER_PAYMENT_METHOD");
							price = obj.getInt("ORDER_PRICE");
							userId = obj.getString("ORDER_USER_ID");
						
							orderList.add(new Order(orderNumber, content, comment, pickup, method, price, userId));
						}
						orderAdapter.notifyDataSetChanged();
						list.invalidate();
						progress.dismiss();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		
	};
	
	AsyncTaskCompleteListener getEventListener = new AsyncTaskCompleteListener(){

		@Override
		public void excuteHttpTask() {
			String url = Util.getUrl("EventInfo");
			
			ArrayList<NameValuePair> value = new ArrayList<NameValuePair>();
			value.add(new BasicNameValuePair("REQUEST_EVENT", "100"));
			
			HttpPostTask http = new HttpPostTask(mContext, value, url, getEventListener);
			http.execute();
		}

		@Override
		public void onTaskComplete(String result, boolean taskOk) {
			Log.v("result","reuslt :" + result);
			if(taskOk){
				int code = -1;
				
				try {
					JSONObject object = new JSONObject(result);
					code = object.getInt("RESULT");

					if(code==NetConstant.NETWORK_SUCCESS){
						JSONArray jArr = object.getJSONArray("ITEM");
						int id;
						String name;
						String content;
						String startTime;
						String endTime;
												
						
						for(int i=0;i<jArr.length();i++){
							JSONObject obj = jArr.getJSONObject(i);
							id= obj.getInt("EVENT_ID");
							name = obj.getString("EVENT_NAME");
							content = obj.getString("EVENT_CONTENT");
							startTime = obj.getString("EVENT_START_TIME");
							endTime = obj.getString("EVENT_STOP_TIME");
							
							eventList.add(new Event(id, name, content, startTime, endTime));
						}
						eventAdapter.notifyDataSetChanged();
						list.invalidate();
						progress.dismiss();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		
	};
	
	String initBtnID;
	String tempString;
	@Override
	public void onClick(View v) {
		if(v==btn){
			switch(btn.getId()){
			case AVERAGE_LIST:{
				averageList.clear();
				progress.show();
				getAverageListener.excuteHttpTask();
				break;
			}
			case MEMBER_LIST:{		
				memberList.clear();
				progress.show();
				getMemberListener.excuteHttpTask();
				break;
			}
			case ORDER_LIST:{
				orderList.clear();
				progress.show();
				getOrderListener.excuteHttpTask();
				break;
			}
			case EVENT_LIST:{
				eventList.clear();
				progress.show();
				getEventListener.excuteHttpTask();
				break;
		}
		}
		}
		if(v == startTimeBtn){
			initBtnID = "S";
			if(cbSurpriseEvent.isChecked()){
				new TimePickerDialog(mContext, mTimeSetListener, mTime, mMinute, false).show();
			} else {
				new DatePickerDialog(mContext, mDateSetListener, mYear, mMonth, mDate).show();
			}
		}else if(v == endTimeBtn){
			initBtnID = "E";
			if(cbSurpriseEvent.isChecked()){
				new TimePickerDialog(mContext, mTimeSetListener, mTime+1, mMinute, false).show();
			} else {
				new DatePickerDialog(mContext, mDateSetListener, mYear, mMonth, mDate+1).show();
			}
		}else if(v == completeBtn) {
			//이벤트 등록.
			eventRegeditListener.excuteHttpTask();
		}
		
	}
	
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    tempString = year +"-"+(monthOfYear+1) + "-"+dayOfMonth ; 
                    updateButtonText();
                }
            };
            
    private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		
		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            tempString = mYear +"-"+mMonth + "-"+mDate+" " + hourOfDay + ":"+minute;

			updateButtonText();
		}
	};
            
    public void updateButtonText(){
    	if(cbSurpriseEvent.isChecked()){
    		if(initBtnID.equalsIgnoreCase("S")){
    			startTimeBtn.setText(tempString);
    		} else
    			endTimeBtn.setText(tempString);
    	} else {
    		if(initBtnID.equalsIgnoreCase("S")){
    			startTimeBtn.setText(tempString+" 00:00");
    		} else
    			endTimeBtn.setText(tempString+" 23:59");    		
    	}
    }
    
    AsyncTaskCompleteListener eventRegeditListener = new AsyncTaskCompleteListener(){

		@Override
		public void excuteHttpTask() {
			String url = Util.getUrl("EventRegidit");
			
			String state;
			if(cbSurpriseEvent.isChecked())
				state = "S";
			else
				state = "N";
			ArrayList<NameValuePair> value = new ArrayList<NameValuePair>();
			value.add(new BasicNameValuePair("EVENT_NAME", etEventTitle.getText().toString()));
			value.add(new BasicNameValuePair("EVENT_CONTENT", etEventContent.getText().toString()));
			value.add(new BasicNameValuePair("EVENT_FLAG", state));
			String startTime = startTimeBtn.getText().toString();
			String endTime = endTimeBtn.getText().toString();
			Log.v("???","date check : " + startTime);
			Log.v("???","date check : " + endTime);
			value.add(new BasicNameValuePair("EVENT_START_TIME", startTime));
			value.add(new BasicNameValuePair("EVENT_STOP_TIME", endTime));

			HttpPostTask http = new HttpPostTask(mContext, value, url, eventRegeditListener);
			http.execute();
		}

		@Override
		public void onTaskComplete(String result, boolean taskOk) {
			Log.v("result","reuslt :" + result);
			if(taskOk){
				int code = -1;
				
				try {
					JSONObject object = new JSONObject(result);
					code = object.getInt("RESULT");
					if(code==NetConstant.NETWORK_SUCCESS){
						Toast.makeText(mContext, "성공적으로 등록되었습니다.!", Toast.LENGTH_SHORT).show();
						startTimeBtn.setText("시작일을 설정해주세요");
						endTimeBtn.setText("종료일을 설정해주세요");
						etEventContent.setText("");
						etEventTitle.setText("");
						
					} else if(code==NetConstant.EVENT_ON_SERVER){
						Toast.makeText(mContext, "이미 깜짝이벤트가 실행중 입니다.!", Toast.LENGTH_SHORT).show();
					} else{
						Toast.makeText(mContext, "서버오류.!", Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		
	};
}
